#pragma once
#include "log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <iostream>
#include <string>
#include <cstring>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

using namespace LogModule;
using func_t = std::function<std::string(const std::string&)>;
const int def_fd = -1;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func)
        :_sockfd(def_fd)
        ,_port(port)
        ,_isrunning(false)
        ,_func(func)
    {
    }

    void Init()
    {
        // 1、创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG((int)LogLevel::FATAL) << "套接字创建失败";
            exit(1);
        }
        LOG((int)LogLevel::FATAL) << "套接字创建成功";
        // 2、创建套接字信息，ip和端口
        struct sockaddr_in local;
        bzero(&local, sizeof(local));  // memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        //使用下面的代码也能对地址进行
        //1、去除点分模式
        //2、转化成int大端序
        //但是缺点是指定了之后代码就只能进行按照指定的IP(内网和那个不是公网的叫啥，客户端和服务器相同)
        //local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG((int)LogLevel::FATAL) << "bind 错误！";
        }
        LOG((int)LogLevel::INFO) << "bind 成功, sockfd: " << _sockfd;
    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, 
            (sockaddr*)&peer, &len);
            if(n > 0)
            {
                //网络序列中的port转话成小端。
                int peer_port = ntohs(peer.sin_port);  
                //4字节风格的网络IP化成点分十进制
                std::string peer_ip = inet_ntoa(peer.sin_addr);
                buffer[n] = 0;
                std::string result = _func(buffer);
                sendto(_sockfd, result.c_str(), result.size(), 0, (sockaddr*)&peer, 
                len);

            }
        }
    }

    ~UdpServer()
    {

    }

private:
    int _sockfd;
    const std::string _ip;
    uint16_t _port;
    bool _isrunning;
    func_t _func;
};